package com.vr.cloudpicture.manager.websocket.handler;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.vr.cloudpicture.enums.SpaceTypeEnum;
import com.vr.cloudpicture.manager.auth.SpaceUserAuthManager;
import com.vr.cloudpicture.manager.auth.model.SpaceUserPermissionConstant;
import com.vr.cloudpicture.model.dto.user.UserLogin;
import com.vr.cloudpicture.model.entity.Picture;
import com.vr.cloudpicture.model.entity.Space;
import com.vr.cloudpicture.service.IPictureService;
import com.vr.cloudpicture.service.ISpaceService;
import com.vr.cloudpicture.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * websocket 拦截器
 *
 * @author hzh
 * @date 2025/05/28
 */
@Slf4j
@AllArgsConstructor
@Component
public class WsHandShakeInterceptor implements HandshakeInterceptor {
    private final IUserService userService;
    private final IPictureService pictureService;
    private final ISpaceService spaceService;
    private final SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 三次握手之前的操作
     */
    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            // 获取请求参数
            String pictureId = servletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)) {
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            // 校验是否登录
            UserLogin loginUser = userService.getLoginUser(servletRequest);
            if (ObjUtil.isEmpty(loginUser)) {
                log.error("用户未登录，拒绝握手");
                return false;
            }
            // 校验用户是否该图片权限
            Picture picture = pictureService.getById(pictureId);
            if (ObjUtil.isEmpty(picture)) {
                log.error("图片不存在，拒绝握手");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space = null;
            if (spaceId != null) {
                space = spaceService.getById(spaceId);
                if (ObjUtil.isEmpty(space)) {
                    log.error("空间不存在，拒绝握手");
                    return false;
                }
                // 只有团队空间才支持协同编辑
                if (!SpaceTypeEnum.TEAM.getValue().equals(space.getSpaceType())) {
                    log.info("非团队空间，拒绝握手");
                    return false;
                }
            } else {
                log.info("公共空间不支持，拒绝握手");
                return false;
            }
            // 是否有编辑权限,这个效率太低了
            // boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_EDIT);
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("用户没有编辑权限，拒绝握手");
                return false;
            }
            // 通过校验，设置一下attributes
            attributes.put("pictureId", Long.valueOf(pictureId));
            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
        }
        return true;
    }

    /**
     * 三次握手之后的操作
     */
    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {
    }
}
